package com.tajiang.business.setting.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gprinter.aidl.GpService;
import com.gprinter.io.GpDevice;
import com.gprinter.service.GpPrintService;
import com.tajiang.business.R;
import com.tajiang.business.bluetooth.PrinterConnectActivity;
import com.tajiang.business.bluetooth.utils.BTPrintUtils;
import com.tajiang.business.common.activity.BaseActivity;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.SharedPreferencesUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.setting.dialog.ChoosePrintNumberDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/7/22.
 */
public class PrintsettingActivity extends BaseActivity {

    public static final int REQUEST_ENABLE_BT = 2;
    public static int DEFAULT_PRINTER_NUM = 1;
    public static final String CONNECT_STATUS = "connect.status";

    @BindView(R.id.layout_bluetooth)
    RelativeLayout layoutBluetooth;
//    @BindView(R.id.sv_print)
//    SwitchView svPrint;
    @BindView(R.id.tv_device_connected)
    TextView tvDeviceConnected;
    @BindView(R.id.tv_print_amount)
    TextView tvPrintAmount;
    @BindView(R.id.btn_print_test)
    Button btnPrintTest;

    private boolean[] state;
    private GpService mGpService = null;
    private PrinterServiceConnection conn = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_print_test)
    public void onPrintTestClick() {

        BTPrintUtils.getInstance().printTestPageClicked();
    }

    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.i("ServiceConnection", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
            state = getConnectState();
            updateViewState();
        }
    }

    @Override
    protected void initTopBar() {
        setTitle("打印设置");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_print);
        ButterKnife.bind(this);
        connection();
    }

    @Override
    protected void initData() {
        tvPrintAmount.setText((String) SharedPreferencesUtils.get(SharedPreferencesUtils.PRINT_AMOUNT, "1"));
//        svPrint.setOpened((Boolean) SharedPreferencesUtils.get(SharedPreferencesUtils.AUTO_PRINT, false));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
//                boolean isConnected = bundle.getBoolean("tv_device_connected", false);
                state = getConnectState();
                updateViewState();
            }
        }
    }

    @OnClick(R.id.layout_bluetooth)
    public void onClick() {
        if ((System.currentTimeMillis() - currentTime) < TIME_IN_MILLS) return;
        currentTime = System.currentTimeMillis();
        openChoosePrinter();
//        intent2Activity(BTPrinterChooseActivity.class);
    }

    @OnClick(R.id.rl_setting_order_num)
    public void onSettingOrderPayClick() {
        ChoosePrintNumberDialog dialog = new ChoosePrintNumberDialog(this);
        dialog.setPrintAmountConfirmListener(new ChoosePrintNumberDialog.onPrintAmountConfirmListener() {
            @Override
            public void onPrintAmountConfirm(String printAmount) {
                tvPrintAmount.setText(printAmount);
            }
        });
        dialog.show();
    }

//    @OnClick(R.id.sv_print)
//    public void onSwitchViewPrintClick() {
//        new AutoPrintDialog(this, svPrint).show();
//    }

    private void updateViewState() {
        if (state[0] == true) {
            tvDeviceConnected.setText("已连接");
            btnPrintTest.setClickable(true);
            btnPrintTest.setBackgroundResource(R.drawable.slt_btn_rect_green);
        } else {
            tvDeviceConnected.setText("未连接");
            btnPrintTest.setClickable(false);
            btnPrintTest.setBackgroundResource(R.drawable.slt_btn_rect_gray);
        }
    }

    private void connection() {
        conn = new PrinterServiceConnection();
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }

    /**
     * 打开蓝牙连接和搜索页面
     */
    public void openChoosePrinter() {

        if (mGpService == null) {
            Toast.makeText(this, "Print Service is not start, please check it", Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkBlueTooth()) {
            Intent intent = new Intent();
            intent.putExtra(CONNECT_STATUS, state[0]);
            intent2ActivityWidthExtrasAndForResult(intent, PrinterConnectActivity.class, 0);
        }
    }

    /**
     * 再次检查蓝牙是否开启（可用）
     *
     * @return
     */
    private boolean checkBlueTooth() {
        // Get local Bluetooth adapter
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (bluetoothAdapter == null) {
            ToastUtils.showShort("蓝牙设备不可用！");
            return false;
        } else {
            // If BT is not on, request that it be enabled.
            // setupChat() will then be called during onActivityResult
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent,
                        REQUEST_ENABLE_BT);
                return false;
            }
        }
        return true;
    }

    public boolean[] getConnectState() {
        boolean[] state = new boolean[GpPrintService.MAX_PRINTER_CNT];
        for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {
            state[i] = false;
        }
        for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {
            try {
                if (mGpService.getPrinterConnectStatus(i) == GpDevice.STATE_CONNECTED) {
                    state[i] = true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return state;
    }

    @Override
    protected void onDestroy() {
        LogUtils.e("onDestroy");
        super.onDestroy();
        if (conn != null) {
            unbindService(conn); // unBindService
        }
    }

    @Override
    public void onBackPressed() {
        PrintsettingActivity.this.finish();
    }
}
